/**
 * 京东联盟商品大字段详情查询模块
 * @version 1.0.0
 * @author 开发者
 * @see {@link https://union.jd.com/openplatform/api/1228|京东联盟API文档}
 */

const {
  normalizePayload,
  normalizeDbConfig,
  buildSignParams,
  buildJdSign,
  parseJdQueryResult,
  persistDocs,
  JD_API_URL,
  mapBigfieldGoodsDoc,
  buildQueryResultMeta
} = require('./@utils')

/**
 * 商品大字段详情查询接口
 *
 * @param {object} payload 请求参数
 * @param {object} [payload.auth] 认证信息
 * @param {object} payload.query 查询参数
 * @param {string[]} [payload.query.itemIds] 商品ID数组
 * @param {string[]} [payload.query.skuIds] SKU ID数组
 * @param {number} [payload.query.sceneId] 场景ID
 * @param {string[]} [payload.query.fields] 查询域集合，可选值：categoryInfo, imageInfo, baseBigFieldInfo, bookBigFieldInfo, videoBigFieldInfo, detailImages
 * @param {object} [payload.query.goodsReq] 完整的商品请求参数
 * @param {object} [payload.options] 可选配置
 * @param {string|object} [payload.options.db] 数据库配置
 * @returns {Promise<{requestParams: object, response: any, queryResult?: object, dbResult?: any}>}
 * @example
 * // 查询所有字段
 * await queryGoodsBigfield({
 *   query: { itemIds: ['123'], sceneId: 1 },
 *   options: { db: 'jd_goods_detail' }
 * })
 *
 * // 只查询类目信息
 * await queryGoodsBigfield({
 *   query: {
 *     itemIds: ['123'],
 *     sceneId: 1,
 *     fields: ['categoryInfo']
 *   }
 * })
 *
 * // 查询多个字段
 * await queryGoodsBigfield({
 *   query: {
 *     itemIds: ['123'],
 *     sceneId: 1,
 *     fields: ['categoryInfo', 'imageInfo', 'detailImages']
 *   }
 * })
 */
async function queryGoodsBigfield(payload) {
  const { auth, query, options } = normalizePayload(payload)

  const { goodsReq, itemIds, skuIds, sceneId, fields } = query

  let finalGoodsReq = goodsReq
  if (!finalGoodsReq) {
    if (!Array.isArray(itemIds) && !Array.isArray(skuIds)) {
      throw new Error('itemIds或skuIds至少提供一个')
    }
    finalGoodsReq = {}
    if (Array.isArray(itemIds)) {
      finalGoodsReq.itemIds = itemIds
    }
    if (Array.isArray(skuIds)) {
      finalGoodsReq.skuIds = skuIds
    }
    if (typeof sceneId === 'number') {
      finalGoodsReq.sceneId = sceneId
    }
    if (Array.isArray(fields) && fields.length > 0) {
      finalGoodsReq.fields = fields
    }
  }

  const { params, appSecret: secret } = buildSignParams({
    appKey: auth.appKey,
    appSecret: auth.appSecret,
    method: 'jd.union.open.goods.bigfield.query',
    businessParams: {
      goodsReq: finalGoodsReq
    },
    timestamp: options.timestamp,
    version: options.version,
    format: options.format,
    signMethod: options.signMethod,
    accessToken: auth.accessToken
  })
  const { sign } = buildJdSign(secret, params)
  const requestParams = {
    ...params,
    sign
  }

  const { status, data } = await uniCloud.httpclient.request(JD_API_URL, {
    method: 'POST',
    data: requestParams,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded',
    timeout: 10000
  })

  if (status !== 200) {
    throw new Error(`京东联盟接口请求失败，HTTP状态码：${status}`)
  }

  const queryResult = parseJdQueryResult(data, 'jd_union_open_goods_bigfield_query_responce')

  let dbResult
  const dbConfig = normalizeDbConfig(options.db)
  if (dbConfig) {
    dbResult = await persistDocs({
      collectionName: dbConfig.collection,
      list: Array.isArray(queryResult?.data) ? queryResult.data : [],
      transform: mapBigfieldGoodsDoc,
      uniqueKeys: dbConfig.uniqueKeys,
      extraDocFields: {
        requestParams,
        queryResultMeta: buildQueryResultMeta(queryResult),
        ...(dbConfig.extraFields || {})
      }
    })
  }

  if (options.debug) {
    return {
      requestParams,
      response: data,
      queryResult,
      dbResult
    }
  }

  return queryResult
}

module.exports = queryGoodsBigfield
